package com.rainy.upload.exception;

import com.google.gson.Gson;
import com.rainy.upload.entity.ResultMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResultMessage exceptionHandler(Exception exception, HttpServletResponse response) {
        ResultMessage resultMessage = new ResultMessage();
        if (exception instanceof AppException) {
            resultMessage.setCode(((AppException) exception).getCode());
            resultMessage.setErrMsg(HtmlUtils.htmlEscape(exception.getMessage()));
            resultMessage.setData("");
        } else if (exception instanceof RuntimeException) {
            resultMessage.setCode(ExceptionCode.RUNTIME_CODE);
            resultMessage.setErrMsg(HtmlUtils.htmlEscape(exception.getMessage()));
            resultMessage.setData("");
        } else if (exception instanceof Exception) {
            resultMessage.setCode(ExceptionCode.EXCEPTION_CODE);
            resultMessage.setErrMsg(HtmlUtils.htmlEscape(exception.getMessage()));
            resultMessage.setData("");
        } else {
            resultMessage.setCode(ExceptionCode.UNKONW_CODE);
            resultMessage.setErrMsg(HtmlUtils.htmlEscape(HtmlUtils.htmlEscape(exception.getMessage())));
            resultMessage.setData("");
        }
        logger.error(new Gson().toJson(resultMessage));
        return resultMessage;
    }

}
